package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author: hea7en
 * @Date: 2024/5/22 4:35 PM
 * @Description: 订单管理实现类
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    AddressBookMapper addressBookMapper;

    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    WeChatPayUtil weChatPayUtil;

    @Autowired
    WebSocketServer webSocketServer;

    @Override
    public OrderSubmitVO orderSubmit(OrdersSubmitDTO ordersSubmitDTO) {
        // 业务数据校验
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        // 收货地址为空，不能下单
        AddressBook address = addressBookMapper.getById(addressBookId);
        if (address==null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 购物车数据为空，不能下单
        List<ShoppingCart> cartList = shoppingCartMapper.getListByUserId(BaseContext.getCurrentId());
        if (cartList==null || cartList.size()==0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 新增订单表数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);
        order.setUserId(BaseContext.getCurrentId());
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setOrderTime(LocalDateTime.now());
        order.setPayStatus(Orders.UN_PAID);
        order.setPhone(address.getPhone());
        order.setConsignee(address.getConsignee());
        order.setAddress(address.getDetail());
        orderMapper.save(order);

        // 新增订单明细表数据
        List<OrderDetail> orderDetailList = cartList.stream().map(cart -> {
            OrderDetail detail = OrderDetail.builder()
                    .name(cart.getName())
                    .image(cart.getImage())
                    .orderId(order.getId())
                    .dishId(cart.getDishId())
                    .setmealId(cart.getSetmealId())
                    .dishFlavor(cart.getDishFlavor())
                    .number(cart.getNumber())
                    .amount(cart.getAmount())
                    .build();
            return detail;
        }).collect(Collectors.toList());
        orderDetailMapper.saveBatch(orderDetailList);

        // 清空购物车数据
        shoppingCartMapper.clean(BaseContext.getCurrentId());

        // 封装返回对象
        OrderSubmitVO orderSubVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();

        return orderSubVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && "ORDERPAID".equals(jsonObject.getString("code"))) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        // 来单提醒，通过WebSocket向客户端浏览器推送消息
        Map<String, Object> objMap = new HashMap<>(12);
        objMap.put("type", 1);
        objMap.put("orderId", ordersDB.getId());
        objMap.put("content","订单号："+outTradeNo);
        String jsonStr = JSON.toJSONString(objMap);
        webSocketServer.sendToAllClient(jsonStr);
    }

    @Override
    public void reminder(Long id) {
        // 根据订单id查询订单
        Orders ordersDB = orderMapper.getById(id);
        // 校验订单是否存在
        if (ordersDB==null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 客户催单
        Map<String, Object> objMap = new HashMap<>(12);
        objMap.put("type", 2);
        objMap.put("orderId", id);
        objMap.put("content","订单号："+ordersDB.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(objMap));
    }

    @Override
    public OrderStatisticsVO getOrderStatistics() {
        // 获取待确认订单数量、已确认订单数量、配送中订单数量
        Integer toBeConfirmed = orderMapper.getCountByStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.getCountByStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.getCountByStatus(Orders.DELIVERY_IN_PROGRESS);
        // 封装返回对象
        OrderStatisticsVO statisticsVO = new OrderStatisticsVO();
        statisticsVO.setToBeConfirmed(toBeConfirmed);
        statisticsVO.setConfirmed(confirmed);
        statisticsVO.setDeliveryInProgress(deliveryInProgress);

        return statisticsVO;
    }

    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 开启自动分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        // 查询订单列表
        Page<Orders> orderPage = orderMapper.getOrderList(ordersPageQueryDTO);

        // 将对象转换成OrderVO
        List<Orders> orderList = orderPage.getResult();
        List<OrderVO> orderVOList = orderList.stream().map(order -> {
            OrderVO orderVO = new OrderVO();
            // 赋值相同属性
            BeanUtils.copyProperties(order, orderVO);
            // 获取订单菜品信息
            String orderDishes  = getOrderDishes(order.getId());
            orderVO.setOrderDishes(orderDishes);
            return orderVO;
        }).collect(Collectors.toList());

        // 封装返回对象
        return new PageResult(orderPage.getTotal(), orderVOList);
    }

    @Override
    public OrderVO getDetails(Long orderId) {
        // 查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderId);
        // 封装订单返回对象
        OrderVO orderVO = new OrderVO();
        orderVO.setOrderDetailList(orderDetailList);
        // 查询订单信息
        Orders orders = orderMapper.getById(orderId);
        // 赋值相同属性
        BeanUtils.copyProperties(orders, orderVO);

        return orderVO;
    }

    @Override
    public void orderConfirm(OrdersConfirmDTO ordersConfirmDTO) {
        // 封装对象
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();

        // 更新订单状态
        orderMapper.update(orders);
    }

    @Override
    public void orderRejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 校验订单状态，只有待确认状态才能拒单
        Orders order = orderMapper.getById(ordersRejectionDTO.getId());
        if (order==null || !Objects.equals(order.getStatus(), Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 已支付的订单需要先退款
        if (Objects.equals(order.getPayStatus(), Orders.PAID)) {
//            String refund = weChatPayUtil.refund(
//                    order.getNumber(),
//                    order.getNumber(),
//                    order.getAmount(),
//                    order.getAmount());
//            log.info("退款结果：{}", refund);
        }

        // 封装对象
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .cancelReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();

        // 更新订单状态
        orderMapper.update(orders);
    }

    @Override
    public void orderCancel(OrdersCancelDTO ordersCancelDTO) {
        // 校验订单状态，已支付的订单需要先退款
        Orders order = orderMapper.getById(ordersCancelDTO.getId());
        if (Objects.equals(order.getPayStatus(), Orders.PAID)) {
//            String refund = weChatPayUtil.refund(
//                    order.getNumber(),
//                    order.getNumber(),
//                    order.getAmount(),
//                    order.getAmount());
//            log.info("退款结果：{}", refund);
        }

        // 封装对象
        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .build();

        // 更新订单状态
        orderMapper.update(orders);
    }

    @Override
    public void orderDelivery(Long orderId) {
        // 校验订单状态，只有待派送的订单才能派送
        Orders order = orderMapper.getById(orderId);
        if (order==null || !Objects.equals(order.getStatus(), Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 封装对象
        Orders orders = Orders.builder()
                .id(orderId)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();

        // 更新订单状态
        orderMapper.update(orders);
    }

    @Override
    public void orderComplete(Long orderId) {
        // 校验订单状态，只有待派送的订单才能完成订单
        Orders order = orderMapper.getById(orderId);
        if (order==null || !Objects.equals(order.getStatus(), Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 封装对象
        Orders orders = Orders.builder()
                .id(orderId)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();

        // 更新订单状态
        orderMapper.update(orders);
    }

    /**
     * 获取订单菜品信息
     * @param orderId
     * @return
     */
    private String getOrderDishes(Long orderId) {
        // 查询订单详情信息
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderId);
        // 封装菜品信息
        String dishStr = orderDetailList.stream().map(detail -> {
            // 拼接：菜品名称+数量
            return detail.getName() + "x" + detail.getNumber();
        }).collect(Collectors.joining(";"));

        return dishStr;
    }
}
